package com.example.demo.utils;

import com.example.demo.config.FileProperties;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Slf4j
@Component
@RequiredArgsConstructor
public class FileUploadUtil {
    private final FileProperties props;
    private Path root;

    @PostConstruct
    public void init() throws IOException {
        root = Paths.get(props.getUploadPath()).toAbsolutePath().normalize();
        Files.createDirectories(root);
    }

    /**
     * 批量保存，返回可访问 URL 列表
     */
    public List<String> save(List<MultipartFile> files) {
        if (files == null || files.isEmpty()) return List.of();
        List<String> urls = new ArrayList<>();
        for (MultipartFile f : files) {
            if (f.isEmpty()) continue;
            String ext = StringUtils.getFilenameExtension(f.getOriginalFilename());
            String name = UUID.randomUUID() + "." + ext;
            try {
                Path target = root.resolve(name);
                Files.copy(f.getInputStream(), target);
                // 对外暴露：/upload/文件名
                urls.add("http://192.168.10.3:8085/upload/" + name);
            } catch (IOException e) {
                throw new RuntimeException("上传失败", e);
            }
        }
        return urls;
    }
}